package sunwin.yoms.web.controller.resource;

import jodd.datetime.JDateTime;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsFunction;
import sunwin.yoms.comm.YomsHelper;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.comm.model.NameAndValueModel;
import sunwin.yoms.comm.model.TimeSpan;
import sunwin.yoms.domain.resource.StadiumDomain;
import sunwin.yoms.domain.resource.SubscribeExceptionDomain;
import sunwin.yoms.service.resource.StadiumService;
import sunwin.yoms.service.resource.SubscribeExceptionService;
import sunwin.yoms.service.resource.SubscribeOrderService;
import sunwin.yoms.web.comm.R;
import sunwin.yoms.web.comm.YomsAjaxAnswer;
import sunwin.yoms.web.comm.YomsController;
import sunwin.yoms.web.comm.resolverArg.YomsArrayParam;
import sunwin.yoms.web.comm.resolverArg.YomsDateParam;
import sunwin.yoms.web.model.SubExceptionAndTimeSpan;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by watson on 2015/11/16.
 */
@Controller
public class SubscribeExceptionController {
    @Autowired
    private SubscribeExceptionService subscribeExceptionService;
    @Autowired
    private SubscribeOrderService subscribeOrderService;
    @Autowired
    private YomsHelper yomsHelper;
    @Autowired
    private StadiumService stadiumService;
    private final String FindSubException = "resource/subException.find";
    private final String CreateSubException = "resource/subException.create";
    private final String EditSubException = "resource/subException.edit";

    /**
     * 查找例外计划
     *
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.FindSubException, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.FindSubException, viewName = FindSubException)
    public ModelAndView showSubExceptionList(SubscribeExceptionDomain domain,
                                             ModelMap modelMap,
                                             @RequestParam(required = false, defaultValue = "1") int pageIndex) throws YomsException, ParseException {
        modelMap.addAttribute("domain1", domain);
        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageIndex(pageIndex);
        List<SubExceptionAndTimeSpan> domains1 = new ArrayList<>();
        List<SubscribeExceptionDomain> domains = subscribeExceptionService.getExceptionList(domain, yomsPage);
        for (int i = 0; i < domains.size(); i++) {
            List<TimeSpan> timeSpans = new ArrayList<>();
            timeSpans = subscribeOrderService.convertLongToTimespans(domains.get(i).getStadiumId(), domains.get(i).getExceptionTimeBucket());

            SubExceptionAndTimeSpan subExceptionAndTimeSpan = new SubExceptionAndTimeSpan();
            subExceptionAndTimeSpan.setSubscribeExceptionDomains(domains.get(i));
            subExceptionAndTimeSpan.setTimeSpans(timeSpans);
            //时间转为字符串
            String tempTimeSpan = "";
            for (TimeSpan timeSpan : timeSpans) {
                tempTimeSpan += timeSpan.getStartTimeString() + "-" + timeSpan.getEndTimeString() + "<br>";
            }
            subExceptionAndTimeSpan.setTimeSpansString(tempTimeSpan);
            domains1.add(subExceptionAndTimeSpan);
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("yomsPage", yomsPage);
        mav.addObject("domains", domains1);
        mav.addObject("sid", domain.getStadiumId());
        return mav;
    }

    /**
     * 增加例外访问页面
     */
    @RequestMapping(value = R.CreateSubException, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.CreateSubException, viewName = CreateSubException)
    public ModelAndView addSubException(int sid) throws YomsException {
        //根据SID获取场馆营业时间
        //根据营业时间将时间段分割成每小时一段的集合
        StadiumDomain domain = stadiumService.getStadiumById(sid);
        ModelAndView mav = new ModelAndView();
        mav.addObject("stadiumId", domain.getStadiumId());
        mav.addObject("stadiumName", domain.getStadiumName());
        return mav;
    }

    /**
     * 创建例外
     *
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.CreateSubException, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.CreateSubException, viewName = CreateSubException)
    @ResponseBody
    public YomsAjaxAnswer addSubExceptions(int stadiumId,
                                           @YomsDateParam JDateTime date1,
                                           @YomsArrayParam List<String> exceptionTimeBucket,
                                           String exceptionContent) throws Exception {
        SubscribeExceptionDomain domain = new SubscribeExceptionDomain();
        domain.setExceptionDate(date1.convertToDate());
        domain.setStadiumId(stadiumId);
        domain.setExceptionContent(exceptionContent);
        //时间转换成时间列表
        List<TimeSpan> timeSpans = (subscribeOrderService.convertStringToTimespan(exceptionTimeBucket));
        domain.setExceptionTimeBucket(subscribeOrderService.convertTimeSpansToLong(timeSpans));
        subscribeExceptionService.addSubException(domain);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 编辑例外访问页面
     */
    @RequestMapping(value = R.EditSubException, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.EditSubException, viewName = EditSubException)
    public ModelAndView editSubException(int id, ModelMap modelMap) throws YomsException {

        SubscribeExceptionDomain domain = subscribeExceptionService.getSubExceptionById(id);
        //查询营业时间
        TimeSpan openTime = stadiumService.getStadiumBusinessTimeSpan(domain.getStadiumId());
        //将场馆营业时间分割成小时段
        List<TimeSpan> openTimeList = subscribeExceptionService.businessHours(openTime);
        //将场馆已经预定的时间分割成小时段
        List<TimeSpan> timeSpans = subscribeOrderService.convertLongToTimespans(domain.getStadiumId(), domain.getExceptionTimeBucket());
        ModelAndView mav = new ModelAndView();
        mav.addObject("subException", domain);
        mav.addObject("openTimeList", openTimeList);
        mav.addObject("timeSpans", timeSpans);
        mav.addObject("stadiumName", domain.getStadiumDomain().getStadiumName());
        mav.addObject("stadiumId", domain.getStadiumDomain().getStadiumId());
        mav.addObject("exceptionDate", domain.getExceptionDate());
        return mav;

    }

    /**
     * 编辑例外
     */
    @RequestMapping(value = R.EditSubException, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.EditSubException, viewName = EditSubException)
    @ResponseBody
    public YomsAjaxAnswer editSubExceptions(int exeptionId,
                                            @YomsArrayParam List<String> exceptionTimeBucket) throws Exception {

        SubscribeExceptionDomain domain=new SubscribeExceptionDomain();
        domain.setExeptionId(exeptionId);
        List<TimeSpan> timeSpans = (subscribeOrderService.convertStringToTimespan(exceptionTimeBucket));
        domain.setExceptionTimeBucket(subscribeOrderService.convertTimeSpansToLong(timeSpans));
        subscribeExceptionService.updateSubException(domain);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 删除例外
     */
    @RequestMapping(value = R.DeleteSusbcription, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.DelSubException)
    @ResponseBody
    public YomsAjaxAnswer delSubException(@YomsArrayParam List<Integer> ids) throws YomsException {
        if (ids != null) {
            for (int id : ids) {
                subscribeExceptionService.delSubException(id);
            }
        }
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 根据场馆ID获取营业时间段
     */
    @RequestMapping(value = R.FindSubExceptionBucket, method = RequestMethod.POST)
    @ResponseBody
    public Object getTimePlanBySid(int sid) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        try {
            List<TimeSpan> timeSpans = subscribeOrderService.getSubscribeDateTimeSpanBySid(sid);
            List<NameAndValueModel> nameAndValueModels = new ArrayList<>();
            for (TimeSpan timeSpan : timeSpans) {
                NameAndValueModel navm = new NameAndValueModel();
                navm.setName(timeSpan.getStartTimeString());
                navm.setValue(timeSpan.getEndTimeString());
                nameAndValueModels.add(navm);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(nameAndValueModels);
            answer.setData(jsonArray.toString());
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject;
    }

    /**
     * 根据场馆ID,日期,获取已经预约的时间段
     */
    @RequestMapping(value = R.SubExcepedBucket, method = RequestMethod.POST)
    @ResponseBody
    public Object getSubExceptedById(int sid,@YomsDateParam JDateTime date1) throws YomsException {
        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        //取得营业时间
        TimeSpan businessTimeSpan = stadiumService.getStadiumBusinessTimeSpan(sid);
        //已经被预约的时间值
        Date date = date1 == null ? null : date1.convertToDate();
        long timeSpanLong = subscribeExceptionService.getSubExcepedTimeById(sid,date);
        //两个时间相与得到已被预约的时间
        int minutes = new JDateTime(businessTimeSpan.getStartTime()).getMinute();
        List<TimeSpan> timeSpans = new ArrayList<>();
        long iter = 2;
        for (int i = 0; i < 63; i++) {
            if ((timeSpanLong & iter) == iter) {
                TimeSpan timeSpan = new TimeSpan();
                timeSpan.setStartTimeString(String.format("%s:%s:00", i, minutes));
                timeSpan.setEndTimeString(String.format("%s:%s:00", i + 1, minutes));
                timeSpans.add(timeSpan);
            }
            iter = iter << 1;
        }
        //将已经被预约的时间传到前台
        try {
            List<NameAndValueModel> nameAndValueModels = new ArrayList<>();
            for (TimeSpan timeSpan : timeSpans) {
                NameAndValueModel navm = new NameAndValueModel();
                navm.setName(timeSpan.getStartTimeString());
                navm.setValue(timeSpan.getEndTimeString());
                nameAndValueModels.add(navm);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(nameAndValueModels);
            answer.setData(jsonArray.toString());
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject;
    }

}
